import { useRef, useEffect } from 'react'
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'
import styles from './Ediitor.module.less'

export const Editor = (props: { readonly: boolean; value: string; lang?: string }) => {
  const monacoEl = useRef<HTMLDivElement>(null)
  const editor = useRef<monaco.editor.IStandaloneCodeEditor>()

  useEffect(() => {
    if (monacoEl.current) {
      editor.current = monaco.editor.create(monacoEl.current, {
        value: props.value,
        language: 'json',
        readOnly: props.readonly
      })
    }

    return () => {
      editor.current?.dispose()
    }
  }, [])

  useEffect(() => {
    editor.current?.updateOptions({ readOnly: props.readonly })
  }, [props.readonly])

  useEffect(() => {
    editor.current?.setValue(props.value)
  }, [props.value])

  useEffect(() => {
    const model = editor.current?.getModel()
    if (!model) return
    if (props.lang) {
      monaco.editor.setModelLanguage(model, props.lang)
    }
  }, [props.lang])

  useEffect(() => {
    const onresize = () => {
      const ele = monacoEl.current
      const ed = editor.current
      if (!ele || !ed) return
      ed.layout({ width: ele.offsetWidth, height: ele.offsetHeight })
    }
    window.addEventListener('resize', onresize)
    const firstResize = setTimeout(onresize, 10)
    return () => {
      clearTimeout(firstResize)
      window.removeEventListener('resize', onresize)
    }
  }, [])

  return <div className={styles.editor} ref={monacoEl}></div>
}
